<template>
  <div class="min-w-fit">
    <!-- Sidebar backdrop (mobile only) -->
    <div class="fixed inset-0 z-40 transition-opacity duration-200 bg-gray-900/30 lg:hidden lg:z-auto"
      :class="sidebarOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'" aria-hidden="true"
      @click="$emit('close-sidebar')"></div>

    <!-- Sidebar -->
    <div id="sidebar" ref="sidebar"
      class="flex lg:flex! flex-col absolute z-40 left-0 top-0 lg:static lg:left-auto lg:top-auto lg:translate-x-0 h-[100dvh] overflow-y-scroll lg:overflow-y-auto no-scrollbar w-64 lg:w-20 lg:sidebar-expanded:!w-64 2xl:w-64! shrink-0 bg-white dark:bg-gray-800 p-4 transition-all duration-200 ease-in-out"
      :class="[variant === 'v2' ? 'border-r border-gray-200 dark:border-gray-700/60' : 'rounded-r-2xl shadow-xs', sidebarOpen ? 'translate-x-0' : '-translate-x-64']"
      @click.stop>
      <!-- Sidebar header -->
      <div class="flex justify-between pr-3 mb-10 sm:px-2">
        <!-- Close button -->
        <button ref="trigger" class="text-gray-500 lg:hidden hover:text-gray-400" @click.stop="$emit('close-sidebar')"
          aria-controls="sidebar" :aria-expanded="sidebarOpen">
          <span class="sr-only">Close sidebar</span>
          <svg class="w-6 h-6 fill-current" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path d="M10.7 18.7l1.4-1.4L7.8 13H20v-2H7.8l4.3-4.3-1.4-1.4L4 12z" />
          </svg>
        </button>
        <!-- Logo -->
        <router-link class="block" to="/">
          <svg class="fill-violet-500" xmlns="http://www.w3.org/2000/svg" width="32" height="32">
            <path
              d="M31.956 14.8C31.372 6.92 25.08.628 17.2.044V5.76a9.04 9.04 0 0 0 9.04 9.04h5.716ZM14.8 26.24v5.716C6.92 31.372.63 25.08.044 17.2H5.76a9.04 9.04 0 0 1 9.04 9.04Zm11.44-9.04h5.716c-.584 7.88-6.876 14.172-14.756 14.756V26.24a9.04 9.04 0 0 1 9.04-9.04ZM.044 14.8C.63 6.92 6.92.628 14.8.044V5.76a9.04 9.04 0 0 1-9.04 9.04H.044Z" />
          </svg>
        </router-link>
      </div>

      <!-- Links -->
      <div class="space-y-8">
        <!-- Pages group -->
        <div v-for="group in menuItems" :key="group.title">
          <h3 class="pl-3 text-xs font-semibold text-gray-400 uppercase dark:text-gray-500">
            <span class="hidden w-6 text-center lg:block lg:sidebar-expanded:hidden 2xl:hidden"
              aria-hidden="true">•••</span>
            <span class="lg:hidden lg:sidebar-expanded:block 2xl:block">{{ group.title }}</span>
          </h3>
          <ul class="mt-3">
            <div v-for="item in group.items" :key="item.title">
              <!-- 处理分组菜单 -->
              <SidebarLinkGroup v-if="item.children" v-slot="parentLink" :active-condition="isGroupActive(item)">
                <a class="block text-gray-800 truncate transition dark:text-gray-100"
                  :class="isGroupActive(item) ? '' : 'hover:text-gray-900 dark:hover:text-white'" href="#0"
                  @click.prevent="parentLink.handleClick(); sidebarExpanded = true">
                  <div class="flex items-center justify-between">
                    <div class="flex items-center">
                      <IconDynamic :name="item.icon" :active="isGroupActive(item)" :size="16" />
                      <span
                        class="ml-4 text-sm font-medium duration-200 lg:opacity-0 lg:sidebar-expanded:opacity-100 2xl:opacity-100">
                        {{ item.title }}
                      </span>
                    </div>
                    <div class="flex ml-2 shrink-0">
                      <IconArrow :expanded="parentLink.expanded" />
                    </div>
                  </div>
                </a>
                <div class="lg:hidden lg:sidebar-expanded:block 2xl:block">
                  <ul class="pl-8 mt-1" :class="!parentLink.expanded && 'hidden'">
                    <li v-for="child in item.children" :key="child.title" class="mb-1 last:mb-0">
                      <router-link :to="child.path" custom v-slot="{ href, navigate, isExactActive }">
                        <a class="block truncate transition"
                          :class="isExactActive ? 'text-violet-500' : 'text-gray-500/90 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200'"
                          :href="href" @click="navigate">
                          <span
                            class="text-sm font-medium duration-200 lg:opacity-0 lg:sidebar-expanded:opacity-100 2xl:opacity-100">
                            {{ child.title }}
                          </span>
                        </a>
                      </router-link>
                    </li>
                  </ul>
                </div>
              </SidebarLinkGroup>

              <!-- 处理单个菜单项 -->
              <router-link v-else :to="item.path" custom v-slot="{ href, navigate, isExactActive }">
                <li class="pl-4 pr-3 py-2 rounded-lg mb-0.5 last:mb-0 bg-linear-to-r"
                  :class="isExactActive && 'from-violet-500/[0.12] dark:from-violet-500/[0.24] to-violet-500/[0.04]'">
                  <a class="block text-gray-800 truncate transition dark:text-gray-100"
                    :class="isExactActive ? '' : 'hover:text-gray-900 dark:hover:text-white'" :href="href"
                    @click="navigate">
                    <div class="flex items-center justify-between">
                      <div class="flex items-center grow">
                        <IconDynamic :name="item.icon" :active="isExactActive" :size="16" class="shrink-0"
                          :class="isExactActive ? 'text-violet-500' : 'text-gray-400 dark:text-gray-500'" />
                        <span
                          class="ml-4 text-sm font-medium duration-200 lg:opacity-0 lg:sidebar-expanded:opacity-100 2xl:opacity-100">
                          {{ item.title }}
                        </span>
                      </div>
                      <div v-if="item.badge" class="flex ml-2 shrink-0">
                        <span
                          class="inline-flex items-center justify-center h-5 px-2 text-xs font-medium text-white rounded-sm bg-violet-400">
                          {{ item.badge }}
                        </span>
                      </div>
                    </div>
                  </a>
                </li>
              </router-link>

            </div>
          </ul>
        </div>

      </div>

      <!-- Expand / collapse button -->
      <div class="justify-end hidden pt-3 mt-auto lg:inline-flex 2xl:hidden">
        <div class="w-12 py-2 pl-4 pr-3">
          <button class="text-gray-400 hover:text-gray-500 dark:text-gray-500 dark:hover:text-gray-400"
            @click.stop="toggleSidebarExpanded">
            <span class="sr-only">Expand / collapse sidebar</span>
            <svg class="text-gray-400 fill-current shrink-0 dark:text-gray-500 sidebar-expanded:rotate-180"
              xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
              <path
                d="M15 16a1 1 0 0 1-1-1V1a1 1 0 1 1 2 0v14a1 1 0 0 1-1 1ZM8.586 7H1a1 1 0 1 0 0 2h7.586l-2.793 2.793a1 1 0 1 0 1.414 1.414l4.5-4.5A.997.997 0 0 0 12 8.01M11.924 7.617a.997.997 0 0 0-.217-.324l-4.5-4.5a1 1 0 0 0-1.414 1.414L8.586 7M12 7.99a.996.996 0 0 0-.076-.373Z" />
            </svg>
          </button>
        </div>
      </div>

    </div>

  </div>
</template>

<script setup lang="ts">
import IconArrow from '../components/icons/IconArrow.vue'
import IconDynamic from '@/components/icons/IconDynamic.vue';

import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import SidebarLinkGroup from '../partials/SidebarLinkGroup.vue'
import { defineComponent, h } from 'vue'; // 导入 defineComponent 和 h 函数
import { isAdmin } from '../utils/authGuard'
import { authApi } from '../api/authService'

defineProps<{
  sidebarOpen: boolean
}>()

const sidebarExpanded = ref(true)
const variant = 'v2'

// 定义 emit 事件
const emit = defineEmits(['close-sidebar'])

// 定义 refs
const trigger = ref<HTMLElement | null>(null)
const sidebar = ref<HTMLElement | null>(null)

// 切换 sidebarExpanded 状态
const toggleSidebarExpanded = () => {
  sidebarExpanded.value = !sidebarExpanded.value
}

// 监听 sidebarExpanded 的变化，更新 body 的类名
watch(sidebarExpanded, (newVal) => {
  const body = document.querySelector('body')
  if (newVal) {
    body?.classList.add('sidebar-expanded')
  } else {
    body?.classList.remove('sidebar-expanded')
  }
})

// 组件挂载时初始化 body 的类名
onMounted(async () => {
  if (sidebarExpanded.value) {
    document.querySelector('body')?.classList.add('sidebar-expanded')
  }
  
  // 更新用户session信息
  try {
    await authApi.updateSessionUserInfo()
  } catch (error) {
    console.error('更新用户信息失败:', error)
  }
})

// 组件卸载时清理 body 的类名
onUnmounted(() => {
  document.querySelector('body')?.classList.remove('sidebar-expanded')
})


const isGroupActive = (item: any) => {
  const currentRoute = useRouter().currentRoute.value;
  if (item.children) {
    return item.children.some((child: any) => currentRoute.path === child.path);
  }
  return false;
};


// 获取当前路由
const currentRoute = useRouter().currentRoute.value

// 检查是否为管理员
const isAdminUser = computed(() => isAdmin())

// 菜单项定义
const menuItems = computed(() => [
  {
    title: 'Pages',
    items: [
      {
        title: 'Dashboard',
        icon: 'dashboard',
        activePath: 'dashboard',
        children: [
          { title: 'Main', path: '/' },
          { title: 'Analytics', path: '/dashboard/analytics' },
          { title: 'Fintech', path: '/dashboard/fintech' }
        ]
      },
      {
        title: 'E-Commerce',
        icon: 'ecommerce',
        activePath: 'ecommerce',
        children: [
          { title: '客户', path: '/ecommerce/customers' },
        ]
      },
      {
        title: 'Messages',
        icon: 'messages',
        path: '/messages',
        badge: 4
      },
      {
        title: 'Reminder',
        icon: 'reminder',
        path: '/reminder',
      },
      
      ...(isAdminUser.value ? [{
        title: '用户管理',
        icon: 'users',
        path: '/users',
      }] : []),
      {
        title: '账户设置',
        icon: 'settings',
        path: '/settings',
      },
    ]
  },
  {
    title: 'More',
    items: [
      {
        title: 'Authentication',
        icon: 'authentication',
        activePath: 'authentication',
        children: [
          { title: 'Signin', path: '/signin' },
          { title: 'Signup', path: '/signup' },
          { title: 'Reset-password', path: '/reset-password' },
        ]
      },
      {
        title: 'Components',
        icon: 'components',
        activePath: 'component',
        children: [
          { title: 'Button', path: '/component/button' },
          { title: 'Input Form', path: '/component/form' },
          { title: 'Dropdown', path: '/component/dropdown' },
          { title: 'Alert & Banner', path: '/component/alert' },
          { title: 'Modal', path: '/component/modal' },
          { title: 'Pagination', path: '/component/pagination' },
          { title: 'Tabs', path: '/component/tabs' },
          { title: 'Breadcrumb', path: '/component/breadcrumb' },
          { title: 'Badge', path: '/component/badge' },
          { title: 'Avatar', path: '/component/avatar' },
          { title: 'Tooltip', path: '/component/tooltip' },
          { title: 'Accordion', path: '/component/accordion' },
          { title: 'Icons', path: '/component/icons' }
        ]
      }
    ]
  }
])
</script>
